package org.apache.ibatis.usage.base;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.usage.dao.UserMapper;
import org.apache.ibatis.usage.model.User;

import javax.swing.text.View;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Name MybatisJdbcOperator
 * @Description: Mybatis 数据库连接操作实现过程
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-04-23 18:02:34
 **/
public class MybatisJdbcOperator {

    public static void run() {
        // Mybatis 数据库连接操作
        // 1. 初始化阶段
        // 1.1 加载全局配置文件
        String config = "mybatis-config.xml";
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream(config);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 1.2 创建数据库连接工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        // 2. 数据库操作阶段
        // 2.1 建立数据库连接
        try (SqlSession session = sqlSessionFactory.openSession()) {
            // 2.2 获取接口映射实现类
            UserMapper userMapper = session.getMapper(UserMapper.class);
            // 2.3 执行数据库操作
            User condition = User.builder().name("杰克").build();
            List<User> users = userMapper.queryUserByName(condition);
            System.out.println(users);
        }
    }

}

